import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { constantRoute } from "./routes";
import NProgress from "nprogress"; // 进度条插件
import "nprogress/nprogress.css"; // 进度条样式
import { useUserStore } from "@/store/modules/user";
// import pinia from "@/store";

const routes: Array<RouteRecordRaw> = [...constantRoute];
// const modules: Record<string, any> = import.meta.glob("./modules/*.ts", { eager: true });
// Object.keys(modules).forEach((key: string) => {
// 	const module = modules[key].default;
// 	routes[0].children?.push(module);
// });

const router = createRouter({
	history: createWebHashHistory(),
	routes,
});

router.beforeEach(async (_to, _from, next) => {
	NProgress.start();
	const userInfo = localStorage.getItem("userInfo");
	const asscessToken = userInfo ? JSON.parse(userInfo)?.asscessToken || "" : "";
	const userStore = useUserStore();
	if (asscessToken) {
		if (_to.path === "/login") {
			next("/");
		} else {
			const username = userStore.username;
			if (username) {
				next();
			} else {
				try {
					// 获取用户信息
					await userStore.storeUserInfo();
					next({ ..._to, replace: true });
				} catch (error) {
					// 登录过期，重新登录
					await userStore.userLogout();
					next({ path: "/login", query: { redirect: _to.path } });
				}
			}
		}
	} else {
		//用户未登录判断
		if (_to.path == "/login") {
			next();
		} else {
			next({ path: "/login", query: { redirect: _to.path } });
		}
	}
});

router.afterEach(() => {
	NProgress.done();
});

export default router;
